package com.pi.shisan.service.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Shisan on 2017/10/16.
 * 反射工具类
 */
public class ReflectUtil {

    /**
     * 获取类下的所有属性，包含继承，私有
     * @param clazz
     * @return
     */
    public static List<Field> getAllField(Class<?> clazz){
        List<Field> list = new ArrayList<Field>();
        Field fields[] = clazz.getDeclaredFields();
        if(fields!=null && fields.length>0){
            for(Field f:fields){
                list.add(f);
            }
        }
        if(clazz.getSuperclass()!=null){
            list.addAll(getAllField(clazz.getSuperclass()));
        }
        return list;
    }

    public static Field getField(Class<?> clazz,String name){
        try {
            return clazz.getDeclaredField(name);
        } catch (NoSuchFieldException e) {
        }
        if(clazz.getSuperclass()!=null) return getField(clazz.getSuperclass(),name);
        return null;
    }

    public static Method getReadMethodByField(Field f) throws Exception{
        PropertyDescriptor pd = new PropertyDescriptor(f.getName(), f.getDeclaringClass());
        return pd.getReadMethod();
    }

    public static Method getWriteMethodByField(Field f) throws Exception{
        PropertyDescriptor pd = new PropertyDescriptor(f.getName(), f.getDeclaringClass());
        return pd.getWriteMethod();
    }

    public static Object invokeMethod(Class<?> clazz,Object instance,String methodName,Class<?> []types,Object...params){
        if(clazz == null) return null;
        try{
            Method m = clazz.getDeclaredMethod(methodName,types);
            return m.invoke(instance,params);
        }catch (Exception e){
        }
        return invokeMethod(clazz.getSuperclass(),instance,methodName,types,params);
    }

}
